package com.viettel.core.bussiness.cms;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.viettel.core.common.utils.LogUtility;
import com.viettel.core.dao.cms.RoleFunctionDAO;
import com.viettel.core.entities.cms.CmsUser;
import com.viettel.core.entities.cms.RoleFunction;
import com.viettel.core.entities.vo.RoleFunctionVO;
import com.viettel.core.exceptions.DataAccessException;

public class PermissionMgrImpl implements PermissionMgr {
	
//	private RoleFunctionDAO roleFunctionDAO ;
	
	private static Map<String, Set<String>> mapRole;
	@Autowired
	RoleFunctionDAO roleFunctionDAO;
	
	public PermissionMgrImpl () {
		if(roleFunctionDAO != null){
			getAllRole();
		}
	}
	

	@Override
	public boolean hasPermission(CmsUser user, String url) {
//		if(mapRole == null){
			getAllRoles();
//		}
		if(mapRole != null && user.getType()!=null){
			HashSet<String> role = (HashSet<String>) mapRole.get(url);
			if(role != null && role.contains(user.getType().name())){
				return true;
			}
		}
		return false;
	}
	
	private void getAllRole(){
		try {
			mapRole = new HashMap<String, Set<String>>();
			List<RoleFunctionVO> lst = roleFunctionDAO.getAllRoleFunction();
			if(lst != null && lst.size() > 0){
				for (RoleFunctionVO item : lst) {
					String key = item.getUrl();
					if(!mapRole.containsKey(key)){
						Set<String> role = new HashSet<String>();
						role.add(item.getRoleName());
						mapRole.put(key, role);
					}else{
						HashSet<String> role = (HashSet<String>) mapRole.get(key);
						if(!role.contains(item.getRoleName())){
							role.add(item.getRoleName());
						}
					}
				}
			}
			
		} catch (DataAccessException e) {
			LogUtility.logError(e, e.toString());
		}
	}
	
	private void getAllRoles(){
		try {
			mapRole = new HashMap<String, Set<String>>();
			List<RoleFunction> lst = roleFunctionDAO.getAllRolesFunction();
			if(lst != null && lst.size() > 0){
				for (RoleFunction child : lst) {
					String key = child.getUrl();
					if(!mapRole.containsKey(key)){
						Set<String> role = new HashSet<String>();
						role.add(child.getRole());
						mapRole.put(key, role);
					}else{
						HashSet<String> role = (HashSet<String>) mapRole.get(key);
						if(!role.contains(child.getRole())){
							role.add(child.getRole());
						}
					}
				}
			}
			
		} catch (DataAccessException e) {
			LogUtility.logError(e, e.toString());
		}
	}

}
